<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: dzf_core.php 4190 2014-09-26 04:22:30Z laoguozhang $
 */

error_reporting(E_ALL); 

define("DZF_PATH",  dirname(__FILE__));


define('STARTTIME', microtime(TRUE)); 
define('IN_DISCUZ', true);

define('DISCUZ_CORE_DEBUG', true); //记录PHP错误信息，可以指定错误信息的类型，参考errro_reporting参数；false为关闭;常用：E_ERROR ^ E_CORE_ERROR ^ E_COMPILE_ERROR ^ E_PARSE
define('DISCUZ_TABLE_EXTENDABLE', true); //设置数据层表类的扩展文件是否具有可扩展性
define('STARTMEMORY', memory_get_peak_usage());
//#start
if(defined('DEBUG_MEMORY')) {
	if(!defined('MEMORY_FUNC')){
		define('MEMORY_FUNC', 'memory_get_peak_usage');
		define('MEMORY_FUNC_PARA', false);
	}
}
//#end

set_exception_handler(array('dzf_core', 'handleException'));

if(DISCUZ_CORE_DEBUG) {
	set_error_handler(array('dzf_core', 'handleError'));
	register_shutdown_function(array('dzf_core', 'handleShutdown'));
}

if(function_exists('spl_autoload_register')) {
	spl_autoload_register(array('dzf_core', 'autoload'));
} else {
	function __autoload($class) {
		return DZF::autoload($class);
	}
}

class dzf_core
{
	private static $_tables;
	private static $_imports;
	private static $_app;
	private static $_memory;
	private static $lmemory;
	private static $_queue;

	public static $appname;

	/**
	 * 当前 application object
	 * @return dzf_base_application|mapi_app
	 */
	public static function app() {
		return self::$_app;
	}

	/**
	 * 创建 application AOP方式, 由应用程序提供切面
	 * 
	 * @return dzf_base_application
	 * */
	public static function creatapp($appname, $cnfpath) {
		if(!is_object(self::$_app)) {
			self::$appname = $appname;
			self::$_app = self::_make_obj('dzf_base_application', 'base', true, array(null, $appname, $cnfpath));
		}
		return self::$_app;
	}
	
	/**
	 * 生成指定类名的实例
	 * @param string $name 类的名称
	 * @param string $type 类型 table|model
	 * @param bool $extendable 是否可扩展方法，即可注册方法执行前后的扩展功能
	 * @param array $p method parameters，实例初始化的参数
	 * @return object
	 */
	protected static function _make_obj($name, $type, $extendable = true, $p = array()) {
	    $cname = $name;
	    if(!isset(self::$_tables[$cname])) {
	        if(!class_exists($cname, true)) {
	            self::import('dzf/'.$type.'/'.$name, false);
	        }
	        if($extendable) {
	            self::$_tables[$cname] = new dzf_base_container();
	            switch (count($p)) {
	                case 0:	self::$_tables[$cname]->obj = new $cname();break;
	                case 1:	self::$_tables[$cname]->obj = new $cname($p[1]);break;
	                case 2:	self::$_tables[$cname]->obj = new $cname($p[1], $p[2]);break;
	                case 3:	self::$_tables[$cname]->obj = new $cname($p[1], $p[2], $p[3]);break;
	                case 4:	self::$_tables[$cname]->obj = new $cname($p[1], $p[2], $p[3], $p[4]);break;
	                case 5:	self::$_tables[$cname]->obj = new $cname($p[1], $p[2], $p[3], $p[4], $p[5]);break;
	                default: $ref = new ReflectionClass($cname);self::$_tables[$cname]->obj = $ref->newInstanceArgs($p);unset($ref);break;
	            }
	        } else {
	            self::$_tables[$cname] = new $cname();
	        }
	    }
	    return self::$_tables[$cname];
	}
	
	/**
	 * 引入 model 对象
	 * @param string $name model名称
	 * @return dzf_base_model|mapi_model_member|mapi_model_portal|mapi_model_article|mapi_model_comment|mapi_model_favorite|mapi_model_subscription|mapi_model_site|mapi_model_setting|mapi_model_update|mapi_model_my
	 */
	public static function m($name) {
		$args = array();
		if(func_num_args() > 1) {
			$args = func_get_args();
			unset($args[0]);
		}
		
		if(strpos($name, '/') !== false) {
			list($appname, $name) = explode('/', $name);
		} else {
			$appname = self::$appname;
		}
		
		return self::_make_obj($appname.'_model_'.$name, 'model', true, $args);
	}
	
	/**
	 * 引用 control 对象
	 * @param string $name
	 * @return dzf_base_control
	 */
	public static function c($name) {
		$args = array();
		if(func_num_args() > 1) {
			$args = func_get_args();
			unset($args[0]);
		}
		
		if(strpos($name, '/') !== false) {
			list($appname, $name) = explode('/', $name);
		} else {
			$appname = self::$appname;
		}
		
		return self::_make_obj($appname.'_control_'.$name, 'control', true, $args);
	}
	
	/**
	 * 引入 table 对象
	 * @param string $name table名称
	 * @return dzf_base_table
	 */
	public static function t($name) {
		static $base;
		$args = array();
		if(func_num_args() > 1) {
			$args = func_get_args();
			unset($args[0]);
		}
		//使用自己的类文件
		//return self::_make_obj(self::$appname.'_table_'.$name, 'table', DISCUZ_TABLE_EXTENDABLE, $args);
		
		//使用DISCUZ的table类文件
		if(strpos($name, '/') !== false) {
			list($appname, $name) = explode('/', $name);
		} else {
			$appname = self::$appname;
		}
		
		return self::_make_obj($appname.'_table_'.$name, 'table', true, $args);
	}
	
	/**
	 * 引入 扩展类 对象
	 * @param string $name 扩展类名称
	 * @return mapi_ext_dc|mapi_ext_dc|mapi_ext_ip
	 */
	public static function ext($name) {
		$args = array();
		if(func_num_args() > 1) {
			$args = func_get_args();
			unset($args[0]);
		}
		
		if(strpos($name, '/') !== false) {
			list($appname, $name) = explode('/', $name);
		} else {
			$appname = self::$appname;
		}
		
		return self::_make_obj($appname.'_ext_'.$name, 'ext', true, $args);
	}

		
	/**
	 * 引入 公共库 对象
	 * @param string $name 库类名称
	 * @return dzf_lib_curl|dzf_lib_ip
	 */
	public static function lib($name) {
		$args = array();
		if(func_num_args() > 1) {
			$args = func_get_args();
			unset($args[0]);
		}
		return self::_make_obj('dzf_lib_'.$name, 'lib', true, $args);
	}
	
	

	/**
	 * 内存读写 object
	 * @return discuz_memory
	 */
	public static function memory() {
		if(!self::$_memory) {
			self::$_memory = new dzf_base_memory();
			$mem = new dzf_base_memory();
			self::$_memory = $mem->init(self::app()->config['memory']);
		}
		return self::$_memory;
	}

	/**
	 * 本地内存读写 object
	 * @return dzf_base_lmemory
	 */
	public static function lmemory() {
		if(!self::$lmemory) {
			self::$lmemory = new dzf_base_lmemory();
		}
		return self::$lmemory;
	}
	
	/**
	 * 队列读写
	 */
	public static function queue() {
		if(!self::$_queue) {
			self::$_queue = new dzf_base_queue();
			$q = new dzf_base_queue();
			self::$_queue = $q->init(self::app()->config['queue']);
		}
		return self::$_queue;
	}

	/**
	 * 引入系统文件
	 * <code>
	 * <?php
	 * D::import('class/task/avatar');
	 * ?>
	 * </code>
	 * 相当于引入代码
	 * <code>
	 * include './source/class/task/task_avatar.php';
	 * </code>
	 * @param type $name 名称
	 * @param type $folder  特定目录
	 * @param bool $force 是否强制加载, 当强制加载的时候, 如果文件不存在则程序终止运行
	 */
	public static function import($name, $force = true) {
		$key = $name;
		if(!isset(self::$_imports[$key])) {
			if(strncmp($name, 'dzf', 3) === 0) {
				$path = DZF_PATH.'/../';
			} else {
				$path = ROOT_PATH.'/application/';//.self::$appname.'/';
			}
			$filename = $name.'.php';
			if(is_file($path.$filename)) {
				self::$_imports[$key] = true;
				//#start
				$_akey = '#file#'.str_replace(array(APP_PATH, "\\"), array('', '/'), realpath($path.$filename));
				self::analysisStart($_akey);
				//#end
				$rt = include $path.$filename;
				//#start
				self::analysisStop($_akey);
				//#end
				return $rt;
			} elseif(!$force) {
				return false;
			} else {
				throw new Exception('Oops! System file lost: '.$filename);
			}
		}
		return true;
	}

	/**
	 * Exception 消息截获
	 * @param Exception $exception
	 */
	public static function handleException($exception) {
		dzf_base_error::exception_error($exception);
	}


	/**
	 * 记录脚本执行时的错误信息
	 * @param int $errno
	 * @param string $errstr
	 * @param string $errfile
	 * @param int $errline
	 */
	public static function handleError($errno, $errstr, $errfile, $errline) {
		if($errno & DISCUZ_CORE_DEBUG) {
			dzf_base_error::system_error($errstr, false, true, false);
		}
	}

	/**
	 * 记录脚本执行结束时的错误信息
	 */
	public static function handleShutdown() {
		if(($error = error_get_last()) && $error['type'] & DISCUZ_CORE_DEBUG) {
			dzf_base_error::system_error($error['message'], false, true, false);
		}
	}

	/**
	 * PHP5 autoload class 支持
	 *
	 * 请注意class目录中文件以及类名的规则
	 * 当使用 class_exists() 检测的时候可以返回 true 或者 false
	 *
	 * @param string $class 类名称
	 * @return boolean
	 *
	 */
	public static function autoload($class) {
		$class = strtolower($class);
				
		$folder = explode('_', $class);
		$count = count($folder);
		if($count > 1) {
			unset($folder[$count-1]);
			$folder[] = $class;
		}
		$file = implode('/', $folder);
		try {
			self::import($file);
			return true;

		} catch (Exception $exc) {

			//note 以下代码主要是为了保持系统函数 class_exists 正常运行，免得中断执行
			$trace = $exc->getTrace();
			foreach ($trace as $log) {
				if(empty($log['class']) && $log['function'] == 'class_exists') {
					return false;
				}
			}
			dzf_base_error::exception_error($exc);
		}
	}

	/**
	 * 开始指定名称的分析项
	 * @param string $name 分析项名称
	 */
	public static function analysisStart($name){
		if(!isset($_GET['debug'])) {return false;}
		$key = 'other';
		if($name[0] === '#') {
			list(, $key, $name) = explode('#', $name);
		}
		if(!isset($_ENV['analysis'])) {
			$_ENV['analysis'] = array();
		}
		if(!isset($_ENV['analysis'][$key])) {
			$_ENV['analysis'][$key] = array();
			$_ENV['analysis'][$key]['sum'] = 0;
		}
		$_ENV['analysis'][$key][$name]['start'] = microtime(TRUE);
		$_ENV['analysis'][$key][$name]['start_memory_get_usage'] = memory_get_usage();
		$_ENV['analysis'][$key][$name]['start_memory_get_real_usage'] = memory_get_usage(true);
		$_ENV['analysis'][$key][$name]['start_memory_get_peak_usage'] = memory_get_peak_usage();
		$_ENV['analysis'][$key][$name]['start_memory_get_peak_real_usage'] = memory_get_peak_usage(true);
	}

	/**
	 * 停止指定名称的分析项
	 * @param string $name 分析项名称
	 * @return array
	 */
	public static function analysisStop($name) {
		if(!isset($_GET['debug'])) {return false;}
		$key = 'other';
		if($name[0] === '#') {
			list(, $key, $name) = explode('#', $name);
		}
		if(isset($_ENV['analysis'][$key][$name]['start'])) {
			$diff = round((microtime(TRUE) - $_ENV['analysis'][$key][$name]['start']) * 1000, 5);
			$_ENV['analysis'][$key][$name]['time'] = $diff;
			$_ENV['analysis'][$key]['sum'] = $_ENV['analysis'][$key]['sum'] + $diff;
			unset($_ENV['analysis'][$key][$name]['start']);
			$_ENV['analysis'][$key][$name]['stop_memory_get_usage'] = memory_get_usage();
			$_ENV['analysis'][$key][$name]['stop_memory_get_real_usage'] = memory_get_usage(true);
			$_ENV['analysis'][$key][$name]['stop_memory_get_peak_usage'] = memory_get_peak_usage();
			$_ENV['analysis'][$key][$name]['stop_memory_get_peak_real_usage'] = memory_get_peak_usage(true);
		}
		return $_ENV['analysis'][$key][$name];
	}
}

class DZF extends dzf_core {}